# 阻塞IO


import requests

import socket


def run():
    html = requests.get("https://www.imooc.com/")
    # 1. 三次握手建立tcp连接
    # 2. 等待服务器响应，在等待过程中cpu属于空转状态
    print(html.text)


def socket_run():
    # 绕过http协议， 直接通过socket获取
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = "www.baidu.com"
    client.connect((host, 80))  # 阻塞IO，意味着这个时候cpu是空闲的
    send_txt = "GET {} HTTP/1.1\r\nHost:{}\r\nConnection:close\r\n\r\n"
    client.send(send_txt.format("/", host).encode("utf8"))

    data = b""
    while 1:
        d = client.recv(1024)   # 一个阻塞的方法，每次读取1024个字节
        if d:
            data += d
        else:
            break

    data = data.decode("utf8")
    print(data)


if __name__ == '__main__':
    socket_run()
